package com.gzw.dms.KJ;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;

import com.gzw.dms.activity.UserTJActivity;
import com.gzw.dms.adapter.SelectUserAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectUserActivity extends BaseActivity {
    private ListView lv_order;
    private Context mContext;
    private ProgressDialog mProgressDialog;
    private TextView tv_seleteAll;
    private TextView tv_title;
    private SelectUserAdapter selectUserAdapter;
    private int refresh = 0;
    private List<UserInfo> userInfoList;
    private boolean isCheck = false;
    private SwipeRefreshLayout mSwipeLayout;
    private View progress;
    private String rownum = "1000";
    private String rows = "0";
    private String realname = "";
    private String user_address = "";
    private List<String> ls_map;
    private List<String> ls_name;
    private TextView tv_select;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_select_user);

    }

    @Override
    protected void initViews() {
        lv_order = (ListView) findViewById(R.id.lv_order);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        progress = findViewById(R.id.include_pb);
        tv_select = (TextView) findViewById(R.id.tv_select);
        tv_title = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_hybh);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

    }
    @Override
    protected void initData() {
        toolbar.setTitle("联系人");
        setSupportActionBar(toolbar);
        mContext = this;
        ls_map = new ArrayList<>();
        ls_name = new ArrayList<>();
        tv_title.setText("选择联系人");
        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute(rownum, rows, realname, user_address
        );
    }
    @Override
    protected void initEvents() {
        tv_seleteAll.setOnClickListener(new myOnClick());
        lv_order.setOnItemClickListener(new mOnItemClick());
        tv_select.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());

        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh = 1;
                ShowOrderTask showOrderTask = new ShowOrderTask();
                showOrderTask.execute(rownum, rows, realname, user_address);
            }
        });
    }


    class mOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ls_map.clear();
            ls_name.clear();
            Map<String, Object> map = new HashMap<>();
            map.put("receiveUserId", userInfoList.get(position).getId());
            map.put("receiveUserName", userInfoList.get(position).getRealName());
            ls_map.add(map.toString());
            ls_name.add(userInfoList.get(position).getRealName());
            Intent mIntent = new Intent();
            //把返回数据存入Intent
            mIntent.putExtra("ls_map", ls_map.toString());
            mIntent.putExtra("ls_name", ls_name.toString());
            //设置返回数据
            setResult(2, mIntent);
            finish();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            refresh = 0;
            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,realname,user_address);
        }else if(resultCode == 2){
            refresh = 0;
            String name = (String) data.getExtras().get("name");

            String dress
                    = (String) data.getExtras().get("dress");

            ShowOrderTask showOrderTask = new ShowOrderTask();
            showOrderTask.execute(rownum, rows,name,dress);
        }

    }

    /**
     * Created by Wangzhiqiang on 2015-10-11
     * 单击事件
     */
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_selectAll:
                    if (userInfoList != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < userInfoList.size(); i++) {
                                SelectUserAdapter.getIsSelected().put(i, true);
                            }
                            dataChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < userInfoList.size(); i++) {
                                if (SelectUserAdapter.getIsSelected().get(i)) {
                                    SelectUserAdapter.getIsSelected().put(i, false);
                                }
                            }
                            dataChanged();
                            isCheck = false;
                        }
                    }
                    break;
                case R.id.tv_select:
                    Intent mIntetn = new Intent();
                    mIntetn.setClass(mContext, UserTJActivity.class);
                    startActivityForResult(mIntetn, 1);
                    break;
                default:
                    finish();
                    break;
            }

        }

    }


    // 刷新listview和TextView的显示
    private void dataChanged() {
        // 通知listView刷新
        selectUserAdapter.notifyDataSetChanged();
    }


    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(true);
                mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
                mProgressDialog.setCancelable(true);
                mProgressDialog.setCanceledOnTouchOutside(false);

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(true);
            }
        }

        protected String doInBackground(String... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("page", params[0]);
            map.put("row", params[1]);
            map.put("realname",params[2]);
            map.put("user_address",params[3]);

            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetMessagePeople"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (refresh == 0) {
//                mSwipeLayout.setRefreshing(false);
                mProgressDialog.dismiss();

            } else if (refresh == 1) {
                mSwipeLayout.setRefreshing(false);
            }

            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else if (result.indexOf("successMsg") > 0){
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    userInfoList = JsonUtil.getPersons(successMsg, new TypeToken<List<UserInfo>>() {
                    }.getType());
                    selectUserAdapter = new SelectUserAdapter(mContext, userInfoList);
                    lv_order.setAdapter(selectUserAdapter);
                }
            }
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu_home; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_vehicle, menu);
        getMenuInflater().inflate(R.menu.menu_sure, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_sure:
                ls_map.clear();
                ls_name.clear();
                if (userInfoList != null){
                    for (int i = 0; i < userInfoList.size(); i++) {
                        if (selectUserAdapter.getIsSelected().get(i)) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("receiveUserId", userInfoList.get(i).getId());
                            map.put("receiveUserName", userInfoList.get(i).getRealName());
//                            ls_map.add(userInfoList.get(i).getId());
                            ls_name.add(userInfoList.get(i).getRealName());
                            ls_map.add(map.toString());
                        }
                    }
                }
                if (ls_map.size() == 0) {
//                    T.showShort(mContext, "请先选择要分配的运单!");
                    finish();
                } else {
//                    Intent mIntetn = new Intent();
//                    mIntetn.setClass(mContext, SelectDriverActivity.class);
//                    mIntetn.putStringArrayListExtra("ls_map", (ArrayList<String>)ls_map);
//                    startActivityForResult(mIntetn, 1);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("ls_map", ls_map.toString());
                    mIntent.putExtra("ls_name", ls_name.toString());
                    //设置返回数据
                    setResult(2, mIntent);
                    finish();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}